<?php
/**
 * This resource gets the accounts accessible to the authenticated user.
 *
 * PHP version 5
 *
 * Copyright 2011, Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @package    SampleWebapp
 * @copyright  2011, Google Inc. All Rights Reserved.
 * @license    http://www.apache.org/licenses/LICENSE-2.0 Apache License,
 *             Version 2.0
 * @author     Eric Koleda <api.ekoleda@gmail.com>
 * @author     Paul Matthews <pmatthews@google.com>
 */

require_once dirname(dirname(__FILE__)) . '/init.php';

/**
 * Returns an array of accounts filtered by their ability to manage clients
 * and their link type.
 * @param array $accounts the accounts to filter
 * @param array $parentLinks a map from customerId to parent link
 * @param boolean $canManageClients if set then only accounts that have a
 *     matching canManageClients value are returned
 * @return array the filtered accounts
 */
function filterAccounts($accounts, $parentLinks, $canManageClients) {
  $filteredAccounts = array();
  foreach ($accounts as $account) {
    $matches = TRUE;
    if (!is_null($canManageClients)) {
      $matches = $matches && ($account->canManageClients == $canManageClients);
    }

    if ($matches) {
      $filteredAccounts[] = $account;
    }
  }
  return $filteredAccounts;
}

// Create result object.
$result = array();

try {
  // Read parameters from the request.
  $canManageClients = !empty($_REQUEST['canManageClients']) ?
    $_REQUEST['canManageClients'] == 'true' : NULL;

  // Retrieve the AdWordsUser from session.
  $user = SessionManager::GetAdWordsUser();

  // Get the ServicedAccountService.
  $managedCustomerService =
    $user->GetService('ManagedCustomerService', ADWORDS_VERSION);

  // Create selector.
  $selector = new Selector();
  // Specify the fields to retrieve.
  $selector->fields = array(
    'Login', 'CustomerId'
  );

  // Get serviced account graph.
  $graph = $managedCustomerService->get($selector);

  // Create map from customerId to parent links.
  $parentLinks = array();
  if (isset($graph->links)) {
    foreach ($graph->links as $link) {
      $parentLinks[$link->clientCustomerId][] = $link;
    }
  }

  // Create map from customerID to account, and find root account.
  $accounts = array();
  $rootAccount = NULL;

  foreach ($graph->entries as $account) {
    $accounts[$account->customerId] = $account;
    if (!array_key_exists($account->customerId, $parentLinks)) {
      $rootAccount = $account;
    }
  }
  $result['rootAccount'] = $rootAccount;

  $result['accounts'] =
    filterAccounts($accounts, $parentLinks, $canManageClients);
} catch (Exception $e) {
  $result['error'] = $e->getMessage();
}

// Return results as JSON.
header('Content-Type: text/javascript; charset=utf8');
print json_encode($result);
